package com.hou.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class Watcher {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.171.128:2181,192.168.171.129:2181,192.168.171.130:2181";
    /**
     * session超时时间
     */
    static final int SESSION_OUTTIME = 5000;//ms

    public static void main(String[] args) throws Exception {
        //重试策略：初试时间为1s 重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        //通过工厂建立连接
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(CONNECT_ADDR) //连接地址
                .sessionTimeoutMs(SESSION_OUTTIME)
                .retryPolicy(retryPolicy)//重试策略
                .build();
        curatorFramework.start();
        //建立一个cache缓存,监听节点
        final NodeCache nodeCache = new NodeCache(curatorFramework, "/father");
        nodeCache.start(true);//第一次启动的时候就会立刻在Zookeeper上读取对应节点的数据内容，并保存在Cache中
        //触发事件为创建节点和更新节点，在删除节点的时候并不触发此操作
        nodeCache.getListenable().addListener(() -> { //NodeCacheListener实现类
            System.out.println("路径为：" + nodeCache.getCurrentData().getPath());
            System.out.println("数据为：" + new String(nodeCache.getCurrentData().getData()));
            System.out.println("状态为：" + nodeCache.getCurrentData().getStat());
            System.out.println("---------------------------------------");
        });

        Thread.sleep(1000);
        curatorFramework.create().forPath("/father", "123".getBytes());

        Thread.sleep(1000);
        curatorFramework.setData().forPath("/father", "456".getBytes());

        Thread.sleep(1000);
        curatorFramework.delete().forPath("/father");

        Thread.sleep(Integer.MAX_VALUE);
    }
}
